package com.ruoyi.project.mobile.user;

import java.math.BigDecimal;
import java.util.Map;

import org.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.ruoyi.common.utils.*;
import com.ruoyi.project.system.coinrecord.domain.HondaCoinRecord;
import com.ruoyi.project.system.coinrecord.service.IHondaCoinRecordService;
import com.ruoyi.project.system.hondaconfig.service.IHondaConfigService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.enums.MemberExamine;
import com.ruoyi.project.system.member.enums.MemberIsVip;
import com.ruoyi.project.system.member.enums.MemberStatus;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.user.service.IUserService;

/**
 * 功能：
 *
 * @author：dell
 * @create：2020/6/20 9:50
 * @version：2020 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
@RestController
@RequestMapping("/api")
public class ApiLoginController {

	@Autowired
	private IMemberService memberService;

	@Autowired
	private IHondaConfigService hondaConfigService;

	@Autowired
	private IHondaCoinRecordService hondaCoinRecordService;

	/**
	 * 小程序登录
	 * @param map
	 * @return
	 */
	@PostMapping("/login")
	@Transactional
	public R findOpenid(@RequestBody Map<String, Object> map){
		JSONObject webAuthorizeInfo = WeixinUtils.getWebAuthorizeInfo((String) map.get("code"));
		String openid = webAuthorizeInfo.getString("openid");
		// 获取会话密钥（session_key）
		String session_key = webAuthorizeInfo.getString("session_key").replace(" ","+");
		//查询数据库是否存在改用户信息
		Member oldMember = this.memberService.findOneByOpenId(openid);
		//如果找不到用户信息 就返回openid
		if(oldMember==null){

			try {
				String decrypts = AesCbcUtil.decrypt(map.get("encryptedData").toString(), session_key,map.get("iv").toString(), "UTF-8");


				if (null != decrypts && decrypts.length() > 0) {
					JSONObject jsons = new JSONObject(decrypts);
					System.out.println("jsons:: "+jsons.toString());
                    /*String gender = jsons.get("gender").toString();
                    MemberUser.setCityId(jsons.get("city").toString()); // 城市
                    MemberUser.setProvinceId(jsons.get("province").toString());// 省份*/
					Member member = new Member();
					member.setUsername(jsons.get("nickName").toString());
					member.setSex((Integer) jsons.get("gender"));
					member.setOpenid(openid);
					member.setHeadpic(jsons.get("avatarUrl").toString());
					member.setStatus(MemberStatus.NORMAL.getValue());
					member.setRecommendNum(0L);
					member.setCoin(new BigDecimal(0));
					member.setRole(1);
					member.setCreated(DateUtils.getNowDate());
					member.setCity(jsons.get("city").toString());
					member.setOrderNum(0);
					member.setHasCar(0);
					member.setVipLv(1);
					member.setSumCoin(new BigDecimal(0));
					if (map.containsKey("introUser")&&!StringUtils.isBlank(map.get("introUser").toString())){
						member.setIntroUser(map.get("introUser").toString());
					}
					this.memberService.insertMember(member);
					if (member.getIntroUser()!=null){
						//修改推荐人的推荐数量
						Member oldIntro = this.memberService.selectMemberById(member.getIntroUser());
						Member intro = new Member();
						intro.setId(member.getIntroUser());
						intro.setRecommendNum(oldIntro.getRecommendNum()+1);
						BigDecimal count = new BigDecimal(100);
						intro.setSumCoin(oldIntro.getSumCoin().add(count));
						intro.setCoin(oldIntro.getCoin().add(count));
						this.memberService.updateCoinMember(intro,oldIntro);
						//推荐成功进行积分反馈
						HondaCoinRecord hondaCoinRecord = new HondaCoinRecord();
						hondaCoinRecord.setStatus(1);
						hondaCoinRecord.setMemberId(intro.getId());
						hondaCoinRecord.setType(0);
						hondaCoinRecord.setGetType(0);
						hondaCoinRecord.setCreated(DateUtils.getNowDate());
						hondaCoinRecord.setNum(count);
						hondaCoinRecord.setResId(member.getId());
						this.hondaCoinRecordService.insertHondaCoinRecord(hondaCoinRecord);
					}
					return RFactory.generateR(member);
				} else {
					return R.error("授权失败");
				}

			} catch (Exception e) {
				e.printStackTrace();
			}


			return RFactory.generateR(webAuthorizeInfo.toString());
		}
		//判断用户是否被禁用
		if(oldMember.getStatus().equals(MemberStatus.DISABLE.getValue())){
			return R.error("账户被禁用,请联系管理员");
		}


		return RFactory.generateR(oldMember);
	}


	/**
	 * 绑定手机号
	 * @param map
	 * @return
	 */
	@PostMapping("/mobile")
	@Transactional
	public R updateMobile(@RequestBody Map<String, Object> map){
		JSONObject webAuthorizeInfo = WeixinUtils.getWebAuthorizeInfo((String) map.get("code"));
		String openid = webAuthorizeInfo.getString("openid");
		// 获取会话密钥（session_key）
		String session_key = webAuthorizeInfo.getString("session_key").replace(" ","+");
		//查询数据库是否存在改用户信息
		Member oldMember = this.memberService.findOneByOpenId(openid);
		if(oldMember==null){
			return R.error("请先授权头像昵称");
		}
		try {
			String decrypts = AesCbcUtil.decrypt(map.get("encryptedData").toString(), session_key,map.get("iv").toString(), "UTF-8");
			if (null != decrypts && decrypts.length() > 0) {

				JSONObject jsons = new JSONObject(decrypts);
				System.out.println("jsons:: "+jsons.toString());
				//更新手机号
				Member member = new Member();
				member.setMobile(jsons.get("purePhoneNumber").toString());
				member.setId(oldMember.getId());
				this.memberService.updateMember(member);
			}else{
				return R.error("授权失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok();
	}

}
